package com.chengyu.eyc.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class SignatureUtils {

	private static final Logger LOG = LoggerFactory.getLogger(SignatureUtils.class);

	private static final String TOKEN = "lichetang4Eyc";

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = digit[mByte & 0X0F];
		return new String(tempArr);
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 *
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		StringBuilder strDigest = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			strDigest.append(byteToHexStr(byteArray[i]));
		}
		return strDigest.toString();
	}

	public static boolean checkSignature(String signature, SortedMap<String, String> params) {
		return StringUtil.equals(signature, createSignature(params));
	}

	public static boolean checkSignature(String signature, String timestamp, String nonce) {

		// 1.将token、timestamp、nonce三个参数进行字典序排序
		String[] arr = new String[] { TOKEN, timestamp, nonce };
		Arrays.sort(arr);

		// 2. 将三个参数字符串拼接成一个字符串进行sha1加密
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			LOG.error(e.getMessage(), e);
		}
		// 3.将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return StringUtil.equalsIgnoreCase(tmpStr, signature);
	}

	/**
	 * 创建SHA1签名
	 * 
	 * @param params
	 * @return SHA1签名
	 */
	public static String createSignature(SortedMap<String, String> params) {
		return sha1Encrypt(sortParams(params));
	}

	/**
	 * 创建SHA1签名
	 * 
	 * @param timeStamp
	 * @param nonce
	 * @return SHA1签名
	 */
	public static String createSignature(String timeStamp, String nonce) {
		SortedMap<String, String> signParams = new TreeMap<>();
		signParams.put("token", TOKEN);
		signParams.put("timeStamp", timeStamp);
		signParams.put("nonce", nonce);
		return createSignature(signParams);
	}

	/**
	 * 生成时间戳
	 * 
	 * @return
	 */
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}

	/**
	 * 使用SHA1算法对字符串进行加密
	 * 
	 * @param str
	 * @return
	 */
	public static String sha1Encrypt(String str) {

		if (str == null || str.length() == 0) {
			return null;
		}

		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		try {

			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes(StandardCharsets.UTF_8));

			byte[] md = mdTemp.digest();
			int ii = md.length;
			char[] buf = new char[ii * 2];
			int k = 0;

			for (int i = 0; i < ii; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}

			return new String(buf);

		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 根据参数名称对参数进行字典排序
	 * 
	 * @param params
	 * @return
	 */
	private static String sortParams(SortedMap<String, String> params) {
		StringBuilder sb = new StringBuilder();
		Set<Entry<String, String>> es = params.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if (StringUtil.isNotBlank(v)) {
				sb.append(k + "=" + v + "&");
			}
		}
		return sb.substring(0, sb.lastIndexOf("&"));
	}

	private SignatureUtils() {

	}

}
